<template>
  <a-form-model ref="form" :model="formData" :rules="rules">
    <a-row>
      <a-col :span="8">
        <a-form-model-item label="质检类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qualityType">
          <a-radio-group v-model="formData.qualityType">
            <a-radio :value="1">免检</a-radio>
            <a-radio :value="2">抽检</a-radio>
            <a-radio :value="3">全检</a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-col>
      <a-col :span="8">
        <a-form-model-item
          v-show="formData.qualityType == 2"
          label="抽检比例"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="qualityNum"
          :rules="{
            required: formData.qualityType == 2,
            message: '质检项不能为空',
            trigger: 'blur',
          }"
        >
          <a-input-number
            v-model="formData.qualityNum"
            placeholder="请输入抽检比例"
            :min="0"
            :max="99"
            :step="1"
            :precision="0"
            style="width: 80%"
          ></a-input-number
          ><span class="input-number-unit">%</span>
        </a-form-model-item>
      </a-col>
      <a-col :span="24" v-show="formData.qualityType != 1">
        <a-form-model-item label="质检模板" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qualityTemplateId">
          <j-url-select-search
            v-model="formData.qualityTemplateId"
            url="/hzkj-product/product/archive/hzArchiveQualityTemplate/list?pageNo=1&pageSize=10"
            queryWord="templateName"
            :optionDiy="optionDiy"
            @change="changeTemplate"
          />
          <a-alert message="提醒： 更换质检模版，会清空下表中模版的质检项目，请谨慎操作。" banner />
        </a-form-model-item>
      </a-col>
      <a-col :span="24">
        <a-form-model-item label="质检说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qualityRemark">
          <a-textarea v-model="formData.qualityRemark" rows="2" placeholder="请输入质检说明" :maxLength="50" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-button v-show="formData.qualityType != 1" type="primary" icon="plus" @click="addQualityItem"
      >添加自定义质检项</a-button
    >
    <a-table
      v-show="formData.qualityType != 1"
      :pagination="false"
      bordered
      :columns="formColumns"
      :data-source="formData.tableData"
      rowKey="sortNum"
      style="margin-top: 20px"
      ref="qualityTable"
    >
      <template #sortSlot>
        <a-icon type="menu" class="sort-handler-ico" title="拖动排序" />
      </template>
      <template #itemTitle> <span v-show="formData.qualityType != 1" class="required-ico">*</span>质检项 </template>
      <template #itemSlot="text, record, index">
        <div v-if="record.source == 1">{{ record.item }}</div>
        <a-form-model-item
          v-else
          :prop="'tableData.' + index + '.item'"
          :rules="{
            required: formData.qualityType != 1,
            message: '质检项不能为空',
            trigger: 'blur',
          }"
        >
          <a-textarea v-model="record.item" rows="3" placeholder="请输入质检项" :maxLength="50" />
        </a-form-model-item>
      </template>
      <template #standardTitle>
        <span v-show="formData.qualityType != 1" class="required-ico">*</span>质检标准
      </template>
      <template #standardSlot="text, record, index">
        <div v-if="record.source == 1">{{ record.standard }}</div>
        <a-form-model-item
          v-else
          :prop="'tableData.' + index + '.standard'"
          :rules="{
            required: formData.qualityType != 1,
            message: '质检标准不能为空',
            trigger: 'blur',
          }"
        >
          <a-textarea v-model="record.standard" rows="3" placeholder="请输入质检标准" :maxLength="200" />
        </a-form-model-item>
      </template>
      <template #urlSlot="text, record">
        <j-upload-oss v-model="record.url" fileType="image" :number="1" />
      </template>
      <span slot="action" slot-scope="text, record, index">
        <a-button type="link" @click="delQualityItem(index)">删除</a-button>
      </span>
    </a-table>
  </a-form-model>
</template>

<script>
import Sortable from 'sortablejs'
import { getAction } from '@/api/manage'

export default {
  props: {
    // 要编辑的产品档案采购信息
    defaultData: {
      type: Object,
    },
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      formData: {
        qualityType: 1,
        qualityTemplateId: '',
        qualityRemark: '',
        qualityNum: undefined,
        tableData: [],
      },
      rules: {
        qualityType: [{ required: true, message: '请选择质检类型!' }],
      },
      formColumns: [
        {
          title: '排序',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'sortSlot' },
        },
        {
          title: '序号',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '来源',
          align: 'center',
          width: 60,
          customRender(text, record) {
            return record.source == 1 ? '模板' : '自定义'
          },
        },
        {
          align: 'center',
          width: 300,
          slots: { title: 'itemTitle' },
          scopedSlots: { customRender: 'itemSlot' },
        },
        {
          align: 'center',
          width: 400,
          slots: { title: 'standardTitle' },
          scopedSlots: { customRender: 'standardSlot' },
        },
        {
          title: '质检示意图(最多1张)',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'urlSlot' },
        },
        {
          title: '操作',
          align: 'center',
          width: 70,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        queryTemplateList: '/hzkj-product/product/archive/hzArchiveQualityTemplate/queryHzArchiveQualityItermByMainId',
      },
    }
  },
  watch: {
    defaultData: {
      handler(val) {
        // 只要有值就赋值给formData
        if (val) {
          const newData = JSON.parse(JSON.stringify(val)) // 深拷贝，避免直接引用导致数据污染
          this.formData = {
            qualityType: newData.other.qualityType,
            qualityTemplateId: newData.other.qualityTemplateId,
            qualityRemark: newData.other.qualityRemark,
            qualityNum: newData.other.qualityNum,
            tableData: newData.qualitys.sort((a, b) => a.sortNum - b.sortNum),
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    optionDiy(result) {
      return result.records.map((item) => {
        return {
          ...item,
          value: item.id,
          text: item.templateName,
        }
      })
    },
    addQualityItem() {
      this.formData.tableData.push({
        sortNum: new Date().getTime(),
        source: 2,
        item: '',
        standard: '',
        url: '',
      })
    },
    delQualityItem(index) {
      this.formData.tableData.splice(index, 1)
    },
    // 根据模板id查询模板质检项并更新到表格中
    queryTemplate() {
      let diyArr = this.formData.tableData.filter((item) => item.source == 2) // 保留自定义项
      diyArr.forEach((item, index) => {
        item.sortNum = index + 1 // 更新自定义项的排序
      })
      if (!this.formData.qualityTemplateId) {
        this.formData.tableData = diyArr
        return
      }
      getAction(this.url.queryTemplateList, { id: this.formData.qualityTemplateId }).then((res) => {
        if (res.success) {
          let templateArr = res.result
            .map((item) => ({
              sortNum: diyArr.length + item.sortNum,
              item: item.item,
              standard: item.standar,
              url: '',
              source: 1, // 标记为模板来源
            }))
            .sort((a, b) => a.sortNum - b.sortNum)
          this.formData.tableData = [...templateArr, ...diyArr] // 合并模板项和自定义项
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    changeTemplate(id, oldId) {
      if (!oldId) {
        // 如果没有旧的ID，说明是第一次选择模板，不需要提示
        this.queryTemplate()
        return
      }
      this.$confirm({
        content: (h) => {
          return h(
            'div',
            {
              domProps: {
                innerHTML: `<div style="padding-left: 40px;">质检模版切换<span style="color: red">将清空根据质检模版带出的质检项</span>你还要继续吗？</div>`,
              },
            },
            []
          )
        },
        onOk: () => {
          // 替换模板
          this.queryTemplate()
        },
        onCancel: () => {
          this.formData.qualityTemplateId = oldId
        },
      })
    },
  },
  mounted() {
    //初始化表格拖动
    this.$nextTick(() => {
      new Sortable(this.$refs.qualityTable.$el.querySelector('tbody'), {
        handle: '.sort-handler-ico',
        animation: 200,
        sort: true,
        onEnd: ({ newIndex, oldIndex }) => {
          //  oldIndex:谁
          //  newIndex:移动到哪儿
          const currRow = this.formData.tableData.splice(oldIndex, 1)[0]
          this.formData.tableData.splice(newIndex, 0, currRow)
        },
      })
    })
  },
}
</script>

<style scoped lang="less">
.required-ico {
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
}
.input-number-unit {
  display: inline-block;
  margin-left: -2px;
  width: 20%;
  color: rgba(0, 0, 0, 0.65);
  font-weight: 400;
  font-size: 14px;
  text-align: center;
  line-height: 30px;
  background-color: #fafafa;
  border: 1px solid #d9d9d9;
  border-radius: 0 4px 4px 0;
}
.sort-handler-ico {
  padding: 10px;
  cursor: move;
}
</style>
